package logic

import (
	"context"
	"fmt"
	"rpc/model/mysql"
	"rpc/model/redis"

	"rpc/internal/svc"
	"rpc/turn"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *turn.UserLoginRequest) (*turn.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Rdb.Get(context.Background(), "sendSmslogin"+in.Tel)

	if get.Val() != in.Code {
		return nil, fmt.Errorf("短信验证码错误")
	}

	u := mysql.User{}

	err := u.FindUser(in.Tel)
	if err != nil {
		return nil, fmt.Errorf("用户查询失败")
	}

	if u.ID == 0 {
		return nil, fmt.Errorf("用户不存在")
	}

	if u.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}
	redis.Rdb.Del(context.Background(), "sendSmslogin"+in.Tel)
	return &turn.UserLoginResponse{
		UserId: int64(u.ID),
	}, nil
}
